<template>
  <div class="top-container">
    <div class="top-item" @click="protectionOriginBack()">
      <router-link to="/protection">
        <div class="page-and-direction">
          <div class="page page-left">
            <div class="page-line-1"></div>
            <div class="page-line-2"></div>
          </div>
          Pools
        </div>
      </router-link>
    </div>
    <div class="top-item">
      <router-link to="/nftPortfolio">
        <div class="page-and-direction">
          View my Nfts
          <div class="page page-right">
            <div class="page-line-1"></div>
            <div class="page-line-2"></div>
          </div>
        </div>
      </router-link>
    </div>
  </div>

  <div class="protection-info">
    <div class="protection-protocol">
      <div><img src="../../assets/about-results-01.svg" alt="" /></div>
      <div>{{ protectionInfo?.Protected }}</div>
    </div>
    <div class="protection-type">
      <div class="info-title">Protection Type</div>
      <div class="info-info">{{ protectionInfo?.ProtectionType }}</div>
    </div>
    <div class="protection-capacity">
      <div class="info-title">Capacity</div>
      <div class="info-info">{{ protectionInfo?.Capacity }}</div>
    </div>
    <div class="protection-useable">
      <div class="info-title">Capacity Occupied</div>
      <div class="info-info">{{ protectionInfo?.Occupied }}</div>
    </div>
    <div class="protection-rate">
      <div class="info-title">Premium Rate</div>
      <div class="info-info">{{ protectionInfo?.["Premium Rate"] }}</div>
    </div>
    <div class="protection-payment">
      <div class="info-title">Underwriting Token</div>
      <div class="info-info">{{ protectionInfo?.UnderwritingToken }}</div>
    </div>
  </div>

  <div class="protection-excute" @mouseup="moveEnd()">
    <div class="protection-agreement">
      Lorem ipsum dolor sit, amet consectetur adipisicing elit. Accusamus,
      architecto laboriosam mollitia molestias sunt, incidunt id nemo eaque quam
      assumenda velit molestiae amet dolorem dolor excepturi fugit. Minima,
      repellat iste? Lorem ipsum dolor sit amet consectetur, adipisicing elit.
      Commodi officia sapiente, autem, architecto dignissimos mollitia ullam
      enim facere quod eum temporibus et a earum ut dolorum? Alias fugit magnam
      nisi!
    </div>

    <div class="protection-buy-or-underwrite">
      <div class="select">
        <div :class="buy" @click="showBuyProtect()">PROTECT</div>
        <div :class="underwrite" @click="showUnderwrite()">UNDERWRITE</div>
      </div>
      <div class="amount-container" v-if="buyProtect == true">
        <div class="amount">
          <div class="amount-title">Coverage</div>
          <div class="amount-input amount-input-left-l">
            <div class="amount-input-box">
              <!-- <input
                v-model="coverage"
                type="text"
                placeholder="0"
                oninput="value=value.replace(/[^\d]/g,'')"
                @keydown="recaculate()"
              /> -->
              <InputNumber
                :value="coverage"
                @change="(e) => (this.coverage = e)"
                :min="0"
              />
            </div>
            <div class="amount-token">USDT</div>
          </div>
        </div>

        <div class="amount">
          <div class="amount-title">Cover period ( 180 Days Most )</div>

          <div class="amount-input amount-input-slider">
            <div class="amount-input-box amount-input-box-slider">
              <Slider
                class="slider-line"
                :max="180"
                @change="sliderChange"
                :value="coverPeriod"
                :marks="marks"
              />
            </div>

            <div class="amount-token amount-token-days">
              <InputNumber
                :value="coverPeriod"
                @change="(e) => (this.coverPeriod = e)"
                :max="180"
                :min="0"
              />
              <div class="amount-token-days-day">Days</div>
            </div>
          </div>
        </div>

        <div class="amount">
          <div class="amount-title amount-title-others">
            Protect For Others
            <div :class="selectForOthers" @click="protectForOthers()">⏷</div>
          </div>
          <div class="amount-input" v-show="protectOtherShow">
            <div class="amount-input-box amount-input-box-others">
              <input
                type="text"
                placeholder="Enter benificiary address here"
                maxlength="42"
                v-model="beneficiary"
                oninput="value=value.replace(/[g-wyzG-WYZ]/g,'')"
              />
            </div>
          </div>
        </div>

        <Button
          type="primary"
          :loading="caculateLoading"
          class="protectBtn"
          @click="caculate()"
        >
          {{ premium }}
        </Button>
        <!-- <div v-if="beforeCaculation == true">{{ premium }}</div>
            <div v-else>
              <div class="pending">
                <ul>
                  <li>
                    <div class="pending-box box1"></div>
                  </li>
                  <li>
                    <div class="pending-box box2"></div>
                  </li>
                  <li>
                    <div class="pending-box box3"></div>
                  </li>
                  <li>
                    <div class="pending-box box4"></div>
                  </li>
                </ul>
              </div>
            </div> -->
        <Button class="protectBtn" type="primary" @click="doBuyCover()">
          Get Protected
        </Button>
      </div>
      <div class="amount-container" v-else>
        <div class="amount">
          <div class="amount-title">Amount</div>
          <div class="amount-input amount-input-left-l">
            <div class="amount-input-box">
              <!-- <input
                v-model="underwriteAmount"
                type="text"
                placeholder="0"
                oninput="value=value.replace(/[^\d]/g,'')"
              /> -->
              <InputNumber
                :value="underwriteAmount"
                @change="(e) => (this.underwriteAmount = e)"
                :min="0"
              />
            </div>
            <div class="amount-token">USDT</div>
          </div>
        </div>

        <div class="caculate-and-pay caculate-and-pay2">
          <div class="caculate-and-pay-content underwriter-alert">
            Every piece of liquidity will be an nft and can be checked in
            portfolio
          </div>
        </div>

        <Button type="primary" class="protectBtn" @click="doUnderwrite()">
          Underwrite
        </Button>
      </div>
    </div>
  </div>
</template>

<script>
import BigNumber from "bignumber.js";
import store from "../../vuex/store";
import { message, Slider, Button, InputNumber } from "ant-design-vue";
import { MetaDefenderAddress } from "../../vuex/contactAddress";
import { add } from "@/utils/math";

export default {
  name: "ProtectionBtc",
  components: { Slider, Button, InputNumber },
  data() {
    return {
      buyProtect: true,
      premium: "Caculate Cost",
      buy: "buy-init",
      marks: { 0: 0, 180: 180 },
      underwrite: "underwrite-init",
      selectForOthers: "select-for-others-unselected",
      protectOtherShow: false,
      beneficiary: "",
      coverPeriod: 180,
      isMoving: false,
      poolAddress: MetaDefenderAddress,
      coverage: "0",
      underwriteAmount: "0",
      protectionInfo: {},
      caculateLoading: false,
    };
  },
  computed: {
    selectedWidth() {
      return ((this.coverPeriod * 95) / 180).toString() + "%";
    },
    globalViewerData() {
      return store.state.web3Data.globalViewerData;
    },
  },
  watch: {
    globalViewerData(newValue) {
      this.initProtectionInfo(newValue);
    },
  },
  mounted() {
    store.dispatch("protectionOriginHideDo");
    this.initProtectionInfo(store.state.web3Data.globalViewerData);
  },
  methods: {
    async initProtectionInfo(value) {
      let protectContract = this.$route.params?.protectionBtc;
      let poolAddressArr = store.state.web3Data.poolAddressArr;
      let res = await store.dispatch("getPremiumRate", {
        amount: Math.pow(10, 18).toString(),
        date: "360",
        contract: protectContract,
      });
      value.map((item) => {
        if (item.protocol === protectContract) {
          this.protectionInfo = {
            Protected: poolAddressArr[item.protocol.toLowerCase()]?.Protected,
            ProtectionType:
              poolAddressArr[item.protocol.toLowerCase()]?.ProtectionType,
            Capacity: `${
              parseInt(item.totalValidCertificateLiquidity.toHexString(), 16) /
              10 ** 18
            } USDT`,
            Occupied: `${(
              (parseInt(item.totalPendingCoverage.toHexString(), 16) /
                parseInt(
                  item.totalValidCertificateLiquidity.toHexString(),
                  16
                ).toFixed(2)) *
              100
            ).toFixed(4)}%`,
            Coverage: `${
              parseInt(item.totalPendingCoverage.toHexString(), 16) / 10 ** 18
            } USDT`,
            "Premium Rate": `${res}%`,
            UnderwritingToken:
              poolAddressArr[item.protocol.toLowerCase()]?.Token,
          };
        }
      });
    },
    protectionOriginBack() {
      store.dispatch("protectionOriginShowAgainDo");
    },
    protectForOthers() {
      if (this.protectOtherShow == false) {
        this.protectOtherShow = true;
        this.selectForOthers = "select-for-others-selected";
      } else {
        this.protectOtherShow = false;
        this.selectForOthers = "select-for-others-unselected";
        this.beneficiary = "";
      }
    },
    showBuyProtect() {
      this.buyProtect = true;
      this.underwrite = "underwrite-init";
      this.buy = "buy-init";
    },
    showUnderwrite() {
      this.buyProtect = false;
      this.buy = "buy-unselected";
      this.underwrite = "underwrite-selected";
    },
    async caculate() {
      if (this.coverage == "0") {
        message.error("Please enter coverage!");
      } else if (this.coverPeriod == "0") {
        message.error("Please enter cover period!");
      } else {
        this.caculateLoading = true;
        let contract = this.$route.params?.protectionBtc;
        let res = await store.dispatch("getPremiumRate", {
          amount: new BigNumber(this.coverage)
            .multipliedBy(Math.pow(10, 18))
            .toFixed(),
          date: this.coverPeriod,
          contract: contract,
        });
        let result = new BigNumber(res).multipliedBy(100).toFixed();
        console.log("这里res===>", res, res * 100, result);
        this.caculateLoading = false;
        this.premium = `${result} USDT for premium \n+ 10.00 USDT for deposit \n= ${add(
          10,
          result
        )} USDT total cost`;
      }
    },
    recaculate() {
      this.premium = "Caculate Cost";
    },

    sliderChange(e) {
      this.coverPeriod = e;
    },
    selectCoverPeriod(e) {
      var a;
      let b = document.getElementById("slider-line-all").offsetWidth;

      a = e.offsetX;
      if (a < 0) {
        a = 0;
      }
      if (a > b) {
        a = b;
      }

      this.coverPeriod = Math.ceil((a * 180) / b);
      if (this.coverPeriod > 180) {
        this.coverPeriod = 180;
      }
      this.isMoving = true;
    },
    moveToSelect(e) {
      if (this.isMoving == true) {
        var a;
        let b = document.getElementById("slider-line-all").offsetWidth;

        a = e.offsetX;
        if (a > b) {
          a = b;
        }
        if (a < 0) {
          a = 0;
        }

        this.coverPeriod = Math.ceil((a * 180) / b);
        if (this.coverPeriod > 180) {
          this.coverPeriod = 180;
        }
      }
    },
    moveEnd() {
      this.isMoving = false;
    },

    async doBuyCover() {
      if (this.coverage == "0") {
        message.error("Please enter coverage!");
      } else if (this.coverPeriod == "0") {
        message.error("Please enter cover period!");
      } else {
        var currentAddress;
        currentAddress = store.state.web3Utils.currentAddressComp;
        if (currentAddress == "") {
          store.dispatch("linkWallet");
        } else {
          // 检查授权
          let allowance = await store.dispatch("getAllowance", {
            owner: currentAddress,
            spender: this.poolAddress,
          });

          if (allowance == 0) {
            store.dispatch("approveUsdtForMetaDefender", {
              spender: this.poolAddress,
            });
          } else {
            var policyHolder;
            if (this.beneficiary == "") {
              policyHolder = currentAddress;
            } else {
              policyHolder = this.beneficiary;
            }
            store.dispatch("buyCover", {
              poolAddress: this.poolAddress,
              coverage: this.coverage,
              coverPeriod: this.coverPeriod,
              policyHolder: policyHolder,
            });
          }
        }
      }
    },

    async doUnderwrite() {
      if (this.underwriteAmount == "0") {
        message.error("Please enter underwrite amount!");
      } else {
        var currentAddress;
        currentAddress = store.state.web3Utils.currentAddressComp;
        //console.log(typeof(currentAddress));
        if (currentAddress == "") {
          store.dispatch("linkWallet");
        } else {
          let allowance = await store.dispatch("getAllowance", {
            owner: currentAddress,
            spender: this.poolAddress,
          });
          console.log(allowance);
          if (allowance == 0) {
            store.dispatch("approveUsdtForMetaDefender", {
              spender: this.poolAddress,
            });
          } else {
            store.dispatch("underwrite", {
              poolAddress: this.poolAddress,
              amount: this.underwriteAmount,
            });
          }
        }
      }
    },
  },
  unmounted() {
    store.dispatch("protectionOriginShowAgainDo");
    console.log("不加载btc");
  },
};
</script>

<style lang='less' scoped>
.top-container {
  width: 90%;
  margin: 0 auto;
  margin-top: 30px;
  font-size: 20px;
  display: flex;
  justify-content: space-between;
  a {
    color: #eff1f6;
    font-weight: 700;
  }
  .top-item {
    width: auto;
    .page-and-direction {
      display: flex;
      align-items: center;
    }
  }
}

.page {
  position: relative;
  height: 30px;
  width: 30px;
  border-radius: 15px;
  background-color: #1649ff;
}

.page > div {
  position: absolute;
  width: 12px;
  height: 2px;
  background-color: #eff1f6;
  left: 7.5px;
}

.page-right > div {
  left: 9.5px;
}

.page > .page-line-1 {
  top: 10px;
}

.page > .page-line-2 {
  top: 17px;
}

.page-left > .page-line-1 {
  transform: rotateZ(-41deg);
}

.page-left > .page-line-2 {
  transform: rotateZ(41deg);
}

.page-right > .page-line-1 {
  transform: rotateZ(41deg);
}

.page-right > .page-line-2 {
  transform: rotateZ(-41deg);
}

.page-left {
  margin-right: 10px;
}

.page-right {
  margin-left: 10px;
}

.protection-info {
  width: 90%;
  margin: 0 auto;
  margin-top: 30px;
  background-image: linear-gradient(#2d21b2, #1649ff);
  border-radius: 20px;
}

.protection-protocol {
  color: #eff1f6;
  font-size: 30px;
  font-weight: 800;
  display: flex;
  align-items: center;
}

.protection-protocol img {
  width: 36px;
  margin-right: 5px;
}

.protection-info > div {
  padding: 5%;
}

.protection-info > div div {
  padding: 2%;
}

.info-title {
  color: #a6acb8;
  font-weight: 600;
  font-size: 18px;
}

.info-info {
  color: #eff1f6;
  font-weight: 600;
  font-size: 18px;
}

.protection-excute > div {
  border: 1px solid #1649ff;
  width: 90%;
  margin: 0 auto;
  margin-top: 30px;
}

.protection-agreement {
  border: none !important;
  /* border-radius: 20px; */
  color: #a0a9bd;
  font-size: 18px;
  line-height: 30px;
}

.protection-buy-or-underwrite {
  height: auto;
  border-radius: 20px;
  color: #eff1f6;
  font-weight: 600;
}

.select {
  display: flex;
  justify-content: space-between;
  height: 35px;
  cursor: pointer;
}

.select > div {
  border-bottom: 1px solid #1649ff;
  width: 50%;
  text-align: center;
  line-height: 35px;
}

.buy-init {
  border-radius: 20px 0 0 0;
  background-color: #1649ff;
}

.buy-unselected {
  border-radius: 20px 0 0 0;
}

.underwrite-init {
  border-radius: 0 20px 0 0;
}

.underwrite-selected {
  border-radius: 0 20px 0 0;
  background-color: #1649ff;
}

.amount-container {
  padding: 20px 0;
  .amount {
    width: 90%;
    margin: 0 auto;
    margin-bottom: 20px;
  }
}

.amount-title-others {
  display: flex;
  align-items: center;
}

.amount-input {
  display: flex;
  border: 1px solid #1649ff;
  border-radius: 12px;
  margin-top: 8px;
  align-items: center;
  height: 35px;
}

.amount-input-left-l {
  border-left: 0px;
  /deep/ .ant-input-number {
    border-top-left-radius: 12px;
    border-bottom-left-radius: 12px;
  }
}

.amount-input-slider {
  border: none;
}

.amount-input-box {
  width: 70%;
}

.amount-input-box-slider {
  position: relative;
  margin-right: 12px;
}

.amount-input-box-others {
  width: 94%;
}

.amount-token-days {
  display: flex;
  align-items: center;
  .amount-token-days-day {
    width: 70%;
  }
}

.amount-token > input {
  display: block;
  background-color: #1a2237;
  width: 40%;
  color: #eff1f6;
  font-weight: 600;
  border: none;
  padding: 0;
  height: 28px;
  padding-left: 2px;
  margin-left: 1px;
}

.select-for-others-unselected {
  height: 20px;
  width: 20px;
  margin-left: 12px;
  border-radius: 15px;
  background-color: #515b72;
  line-height: 20px;
  text-align: center;
  cursor: pointer;
  font-size: 15px;
  transition: all 0.3s linear;
}

.select-for-others-selected {
  height: 20px;
  width: 20px;
  margin-left: 12px;
  border-radius: 15px;
  background-color: #1649ff;
  line-height: 20px;
  text-align: center;
  transform: rotateZ(180deg);
  cursor: pointer;
  font-size: 15px;
  transition: all 0.3s linear;
}

.amount-input-box > input {
  display: block;
  border: none;
  background-color: #1a2237;
  color: #eff1f6;
  border-radius: 10px;
  padding-left: 10px;
  width: 100%;
  margin: 0 auto;
  font-size: 20px;
}

.amount-token {
  background-color: #1649ff;
  border-radius: 0 10px 10px 0;
  height: 100%;
  width: 30%;
  text-align: center;
  line-height: 33px;
  cursor: pointer;
  min-width: 100px;
}

.caculate-and-pay {
  width: 90%;
  margin: 0 auto;
  margin-top: 20px;
  height: 45px;
  position: relative;
  cursor: pointer;
}

.caculate-premium-result {
  border: 1px solid #1649ff;
  border-radius: 10px;
  width: 90%;
  margin: 0 auto;
  margin-top: 20px;
  height: 90px;
  position: relative;
  cursor: pointer;
  background-color: #1649ff;
  white-space: pre-line;
}

.caculate-and-pay2 {
  height: 120px;
  background-color: #515b72;
  border: #515b72 1px solid;
}

.caculate-and-pay-excute {
  border: #1649ff 1px solid;
  background-color: #1649ff;
  margin-bottom: 20px;
}

// .caculate-and-pay:hover,
// .caculate-and-pay-excute:hover {
//   border: #2d21b2 1px solid;
//   background-color: #2d21b2;
// }

.caculate-and-pay-content {
  margin: auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  line-height: 30px;
  text-align: center;
}

.premium-result {
  width: 70%;
  margin: auto;
  height: 60px;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  line-height: 20px;
  text-align: left;
}

.underwriter-alert {
  width: 90%;
  height: 110px;
  line-height: normal;
  text-align: justify;
}

.pending {
  width: 40%;
  height: 20px;
  margin: auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.pending > ul {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pending-box {
  height: 15px;
  width: 15px;
  border-radius: 7.5px;
  background-color: #eff1f6;
  animation: size-change 1s linear infinite;
}

.box2 {
  animation-delay: 0.25s;
}

.box3 {
  animation-delay: 0.5s;
}

.box4 {
  animation-delay: 0.75s;
}

@keyframes size-change {
  0% {
    height: 15px;
    width: 15px;
    border-radius: 7.5px;
  }

  25% {
    height: 20px;
    width: 20px;
    border-radius: 20px;
  }

  50% {
    height: 15px;
    width: 15px;
    border-radius: 7.5px;
  }

  75% {
    height: 15px;
    width: 15px;
    border-radius: 7.5px;
  }

  100% {
    height: 15px;
    width: 15px;
    border-radius: 7.5px;
  }
}

@media (min-width: 750px) {
  .protection-info {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .protection-info > div {
    padding: 2%;
    width: 28%;
  }

  .protection-info > div div {
    padding: 2%;
  }

  .protection-excute {
    display: flex;
    width: 90%;
    margin: 0 auto;
    justify-content: space-between;
  }

  .protection-excute > div {
    border: 1px solid #1649ff;
    width: 40%;
    margin: 0;
    margin-top: 30px;
  }

  .protection-agreement {
    width: 55% !important;
  }
}
/deep/ .ant-slider-track {
  background-color: @color-primary;
}
/deep/ .ant-slider-mark-text {
  color: #fff;
  height: 12px;
  font-size: 12px;
  transform: translateX(-50%) scale(0.6) !important;
}
.ant-slider-with-marks {
  margin-bottom: 0;
  margin-top: 0;
}
.protectBtn {
  display: flex;
  width: 90%;
  margin: auto 5%;
  margin-top: 12px;
  height: auto;
  min-height: 36px;
  align-items: center;
  justify-content: center;
}
/deep/ .ant-btn > span {
  white-space: nowrap;
  white-space: pre-line;
  font-weight: 500;
}
</style>